/**
 * 
 */
package com.iwords.api.web.action;

/**
 * @author       BOLIN.HBC 
 * @time         2011-3-6    
 * @description  用户的操作SERVLET       
 */
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.constants.Constants;
import com.iwords.service.UserServiceLocal;
import com.iwords.service.object.FeedbackEntity;
import com.iwords.service.object.UserEntity;
import com.iwords.service.object.UserSysConfigEntity;
import com.iwords.service.object.UserVacation;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.DateUtils;
import com.iwords.utils.Md5;
import com.iwords.utils.StringUtils;
import com.iwords.api.web.base.BaseAction;
import com.iwords.ejb.SchoolFacade;
import com.iwords.ejb.TeacherEntityFacade;
import com.iwords.ejb.UserEntityFacade;
import com.iwords.ejb.entity.School;
import com.iwords.service.object.TeacherEntity;

@WebServlet(name = "userAction", urlPatterns = {"/user"})
public class UserAction extends BaseAction<UserEntity> {

    private static final long serialVersionUID = 1L;
    @EJB
    UserServiceLocal userService;

    public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        String action = req.getParameter("action");

        if (Constants.REGISTER_ACTION.equals(action)) {
            doRegister(req, res);
        } else if (Constants.FIND_ACTION.equals(action)) {
            doFind(req, res);
        } else if (Constants.LOGIN_ACTION.equals(action)) {

            doLogin(req, res);
        } else if (Constants.CHECKUSERNAME_ACTION.equals(action)) {
            doCheckUserName(req, res);
        } else if (Constants.UPDATE_ACTION.equals(action)) {
            doUpdateUser(req, res);
        } else if (Constants.FIND_USER_SYSCONFIG.equals(action)) {
            doFindUserSysConfig(req, res);
        } else if (Constants.SAVE_USER_SYSCONFIG.equals(action)) {
            doSaveUserSysConfig(req, res);
        } else if (Constants.LATEST_FEEDBACK.equals(action)) {
            doFindLatestFeedbacks(req, res);
        } else if (Constants.ADD_FEEDBACK.equals(action)) {
            doAddFeedback(req, res);
        } else if (Constants.CHECK_USER_STATUS.equals(action)) {
            doCheckUserStatus(req, res);
        } else if (Constants.USER_LOAD_AD.equals(action)) {
            loadAd(req, res);
        }

    }
    @EJB
    UserEntityFacade userFacade;
    @EJB
    TeacherEntityFacade teacherFacade;
    @EJB
    SchoolFacade schoolFacade;

    /**返回用户的所在学校logo信息。*/
    private void loadAd(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        JSONObject defaultValue = new JSONObject();
        result.put(Constants.DEFAULT_VALUE, defaultValue);

        String useridStr = req.getParameter("userid");
        System.out.println("useridStr=" + useridStr);
        UserEntity user = userFacade.findByUsername(useridStr);

        System.out.println("UserAction.loadAd() user = " + user);
        System.out.println("UserAction.loadAd() user.getTeacherid() = " + user.getTeacherid());
        if (user.getTeacherid() != null) {
            TeacherEntity teacher = teacherFacade.find(user.getTeacherid());
            System.out.println("UserAction.loadAd() teacher = " + teacher + " teacher.getTeacherName() = "+teacher.getTeachername());
            if (teacher != null) {
                System.out.println("UserAction.loadAd() teacher.getSchoolId() = " + teacher.getSchoolId());
                School school = schoolFacade.find(teacher.getSchoolId());
                System.out.println("UserAction.loadAd() school = " + school);
                if (school != null) {
                    defaultValue.put("image", school.getLogo());
                }
            }
        }
        jsonPrint(res, result);
    }

    private void doCheckUserStatus(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        JSONObject result = new JSONObject();
        String useridStr = req.getParameter("userid");
        String flag = req.getParameter("error");

        //伪实现，后期需要根据实际情况进行修改 by fzc
        if ("false".equals(flag)) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("用户帐户不可用！"));
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        }

        jsonPrint(res, result);
    }

    private void doAddFeedback(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {

        JSONObject result = new JSONObject();

        String useridStr = req.getParameter("userid");
        Long userid = null;

        if (StringUtils.isNotBlank(useridStr)) {

            userid = Long.parseLong(useridStr);

        }
        FeedbackEntity feedback = new FeedbackEntity();
        feedback.setComments(CodeUtils.decode(req.getParameter("comments")));

        try {
            boolean success = userService.addFeedback(userid, feedback);
            if (success) {
                result.put(Constants.IS_SUCCESS, Boolean.TRUE);
            } else {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("提交反馈信息失败，请稍候再试！"));
            }


        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("系统异常"));
        }


        jsonPrint(res, result);
    }

    private void doFindLatestFeedbacks(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        JSONObject result = new JSONObject();

        try {
            List<FeedbackEntity> list = userService.findLatestFeedbacks();
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);

            JSONArray defaultValue = new JSONArray();
//			JSONObject defaultValue = new JSONObject();
            for (FeedbackEntity feedback : list) {
                JSONObject re = new JSONObject();
                re.put("comments", feedback.getComments());
                //re.put("comments0", CodeUtils.encode(feedback.getComments()));

                re.put("responses", feedback.getResponses());
                re.put("username", feedback.getUser().getUsername());
                re.put("createtime", DateUtils.getDateStr(feedback.getCreatetime()));
                defaultValue.put(re);
            }

            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            log.error("feedbacks error!", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询反馈信息失败"));
        }
        jsonPrint(res, result);
    }

    private void doSaveUserSysConfig(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {

        Enumeration<String> queryKeyNames = req.getParameterNames();
        UserEntity user = initEntity(req);
        // List<UserSysConfigEntity> sysConfigs = new
        // ArrayList<UserSysConfigEntity>();
        JSONObject result = new JSONObject();

        while (queryKeyNames.hasMoreElements()) {
            String queryKey = queryKeyNames.nextElement();
            if (Constants.whiteKey.contains(queryKey)) {
                continue;
            } else {
                UserSysConfigEntity sysConfig = new UserSysConfigEntity();
                sysConfig.setConfigkey(queryKey);
                sysConfig.setConfigvalue(req.getParameter(queryKey));
                user.addSysConfig(sysConfig);
            }
        }

        if (userService.updateUserSysConfig(user)) {
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("系统错误，请稍候重试"));
        }
        jsonPrint(res, result);

    }

    private void doFindUserSysConfig(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        String useridStr = req.getParameter("userid");
        Long userid = null;
        JSONObject result = new JSONObject();
        if (StringUtils.isNotBlank(useridStr)) {

            userid = Long.parseLong(useridStr);

            UserEntity user = null;

            try {
                user = userService.find(userid);
                result.put(Constants.IS_SUCCESS, Boolean.TRUE);

//				JSONArray defaultValue = new JSONArray();
                JSONObject defaultValue = new JSONObject();
                for (UserSysConfigEntity sysConf : user.getUserSysConfigs()) {
                    defaultValue.put(sysConf.getConfigkey(), sysConf.getConfigvalue());

                }

                result.put(Constants.DEFAULT_VALUE, defaultValue);
            } catch (Exception e) {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("查询用户配置信息失败"));
            }
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("用户不存在"));

        }

        jsonPrint(res, result);

    }

    private void doUpdateUser(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        UserEntity user = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);

        try {
            userService.edit(user);

        } catch (Exception e) {
            log.error("修改用户信息失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));

        }

        jsonPrint(res, result);

    }

    public void doLogin(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        UserEntity user = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);

        try {
            user = userService.findUser(user);
            if (user != null) {
                JSONObject defaultValue = new JSONObject();
                defaultValue.put("currentlib", user.getCurrentlib());
                defaultValue.put("userid", user.getUserid());
                defaultValue.put("username", user.getUsername());
                defaultValue.put("nickname", user.getNickname());
                defaultValue.put("birthday", getBirthdayStr(user.getBirthday()));
                defaultValue.put("messageid", user.getMessageid());
                defaultValue.put("message", CodeUtils.encode(user.getMessage()));
                defaultValue.put("messagetype", user.getType());
                defaultValue.put("birthday", getBirthdayStr(user.getBirthday()));
                defaultValue.put("gender", user.getGender());
                result.put("defaultValue", defaultValue);
            } else {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("用户不存在或者密码错误"));
            }
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询用户失败"));

        }

        jsonPrint(res, result);

    }

    public void doCheckUserName(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        UserEntity user = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);

        try {
            boolean isContain = userService.isContain(user);
            result.put("defaultValue", !isContain);
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询用户失败"));

        }

        jsonPrint(res, result);
    }

    public void doRegister(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        UserEntity user = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        StringBuilder error = new StringBuilder();
        if (!StringUtils.isNotBlank(user.getUsername())) {
            error.append("用户名不能为空,");

        }
        if (!StringUtils.isNotBlank(user.getPassword())) {
            error.append("用户密码不能为空,");

        }
        //昵称先可以为空 支持快速注册
//		if (!StringUtils.isNotBlank(user.getNickname())) {
//			error.append("用户昵称不能为空,");
//
//		}
        if (userService.isContain(user)) {

            error.append("该用户已经存在,");
        }
        if (error.length() == 0) {
            try {
                Date now = new Date();
                user.setCreatetime(now);
                user.setUpdatetime(now);
                UserVacation userVacation = new UserVacation();
                user.setUserVacation(userVacation);
                userVacation.setUser(user);
                userVacation.setCreatetime(now);
                userVacation.setUpdatetime(now);
                userVacation.setVacationCount(7L);//默认7天年假
                userVacation.setExpireDate(DateUtils.getFormatDateTime(DateUtils.getFormatDateTime(DateUtils.getDateBeforeOrAfter(now, 7), "yyyyMMdd") + " 23:59:59", "yyyyMMdd hh:mm:ss"));

                userService.create(user);
            } catch (Exception e) {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("创建用户失败"));
            }

        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(error.substring(0, error.length() - 1)));

        }

        jsonPrint(res, result);
    }

    public void doFind(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        UserEntity user = initEntity(req);
        try {
            user = userService.find(user.getUserid());
            if (user != null) {
                JSONObject dedaultValue = new JSONObject();
                dedaultValue.put("username", user.getUsername());
                dedaultValue.put("nickname", user.getNickname());
                dedaultValue.put("birthday", getBirthdayStr(user.getBirthday()));
                dedaultValue.put("password", user.getPassword());
                dedaultValue.put("qq", user.getQq());
                dedaultValue.put("phone", user.getPhone());
                dedaultValue.put("gender", user.getGender());
                result.put("defaultValue", dedaultValue);
            } else {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("该用户不存在"));

            }
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询用户失败"));
        }
        jsonPrint(res, result);

    }

    public UserEntity initEntity(HttpServletRequest req) {

        UserEntity user = new UserEntity();
        String userid = req.getParameter("userid");
        if (StringUtils.isNotBlank(userid)) {

            user.setUserid(Long.parseLong(req.getParameter("userid")));
        }
        user.setUsername(CodeUtils.decode(req.getParameter("username")));
        user.setPassword(Md5.compute(CodeUtils.decode(req.getParameter("password"))));
        user.setNickname(CodeUtils.decode(req.getParameter("nickname")));
        user.setPhone(CodeUtils.decode(req.getParameter("phone")));
        user.setQq(CodeUtils.decode(req.getParameter("qq")));
        user.setGender(req.getParameter("gender"));
        String birthday = req.getParameter("birthday");
        if (StringUtils.isNotBlank(birthday)) {

            user.setBirthday(DateUtils.getDate_yyyyMMdd(CodeUtils.decode(birthday)));
        }
        return user;

    }

    private String getBirthdayStr(Date date) {
        if (date != null) {
            SimpleDateFormat df;
            try {
                df = new SimpleDateFormat("yyyy-MM-dd");
                return df.format(date);
            } catch (Exception e) {
                return "";
            }
        } else {
            return "";
        }
    }
}
